<template>
  <div class="container">
    <el-dialog :title="setTitle" :visible.sync="dialogVisible" @close='closeDialog' :close-on-click-modal='false'>
      <el-form :model="dataForm" ref="dataForm" :rules="dataRule" size="mini" label-width="120px" class="common-dialog-height" v-loading="formLoading">
        <el-form-item label="类型：" prop="menuType">
          <el-radio-group v-model="dataForm.menuType" @change="handlerRadioChange" >
            <el-radio :disabled="inputDisabled" v-for="(item, index) in radioTypeList" :label="index + 1" :key="index + 1">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="setName.label + '名称：'" prop="menuName">
          <el-input v-model="dataForm.menuName" :placeholder="setName.placeholder" width="200px" clearable></el-input>
        </el-form-item>
        <el-form-item :label="setAlias.label + '别名：'" prop="menuAlias">
          <el-input v-model="dataForm.menuAlias" :placeholder="setAlias.placeholder" clearable></el-input>
        </el-form-item>
        <el-form-item :label="setParentName" prop="pid">
          <el-popover ref="menuPopover" placement="bottom-start" trigger="click" width="420">
            <el-tree
              :data="treeMenu"
              ref="treeMenu"
              node-key="id"
              :default-expanded-keys="[0]"
              :expand-on-click-node="false"
              highlight-current
              style="max-height: 260px;overflow: auto"
              @current-change="handleTreeCurrentChange"
            >
              <span class="custom-tree-node" slot-scope="{node, data}">
                <span v-if="data.type === 1"><i class="el-icon-folder"></i> [目录] </span>
                <span v-else-if="data.type === 2"><i class="el-icon-menu"></i> [菜单] </span>
                <span v-else-if="data.type === 3"><i class="el-icon-set-up"></i> [操作] </span>
                <span>{{ data.alias }}</span>
              </span>
            </el-tree>
            <el-button slot="reference" style="width: 100%" v-text="dataForm.pname"></el-button>
          </el-popover>
          <el-input v-model="dataForm.pid" type="hidden" style="display: none"></el-input>
        </el-form-item>
        <el-form-item v-if="menuType !== 3" label="图标：" prop="menuIcon" >
          <el-input v-model="dataForm.menuIcon" placeholder="请输入图标的class名称"></el-input>
        </el-form-item>
        <el-form-item v-if="menuType === 2" label="菜单路由：" prop="menuPath">
          <el-input v-model="dataForm.menuPath" placeholder="目录名称/一级菜单名称/二级菜单名称..."></el-input>
        </el-form-item>
        <el-form-item v-if="menuType === 3" label="操作标识：" prop="menuPerm">
          <el-input v-model="dataForm.menuPerm" placeholder="目录名称:一级菜单名称:二级菜单名称...:操作"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="menuOrder">
          <el-input-number v-model="dataForm.menuOrder" controls-position="right" :min="1" :max="99"></el-input-number>
          <span> Tips: 数字越小，排序越前</span>
        </el-form-item>
        <el-form-item label="描述：" prop="menuDesc">
          <el-input v-model="dataForm.menuDesc" type="textarea" :rows="3" placeholder="请输入菜单描述" maxlength="100" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="formDataSubmit()">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  export default {
    data () {
      var validatePath = (rule, value, callback) => {
        if (this.menuType === 2 && !/\S/.test(value)) {
          callback(new Error('请输入菜单路由！'))
        } else {
          callback()
        }
      }
      var validateFlag = (rule, value, callback) => {
        if (this.menuType === 3 && !/\S/.test(value)) {
          callback(new Error('请输入操作标识！'))
        } else {
          callback()
        }
      }
      return {
        dialogType: '',
        menuId: null,
        menuType: 1,
        dialogVisible: false,
        formLoading: false,
        radioTypeList: ['目录', '菜单', '操作'],
        dataForm: {
          menuName: null,
          menuAlias: null,
          pid: null,
          pname: '选择上级资源',
          menuIcon: null,
          menuType: 1,
          menuPerm: null,
          menuPath: null,
          menuOrder: 99,
          menuDesc: null
        },
        dataRule: {
          menuName: [{ required: true, message: '名称不可为空!', trigger: 'blur' }],
          menuAlias: [{ required: true, message: '别名不可为空!', trigger: 'blur' }],
          pid: [{ required: true, message: '请选择上级资源!'}],
          menuPath:[{ validator: validatePath, trigger: 'blur' }],
          menuPerm:[{ validator: validateFlag, trigger: 'blur' }]
        },
        treeMenu: [],
        treeProps: {
          children: 'children'
        }
      }
    },
    computed: {
      inputDisabled() {
        return this.dialogType === 'edit'
      },
      setTitle() {
        const titleF = this.dialogType === 'add' ? '新增' : '编辑'
        let titleB = ''
        if (this.menuType === 2) {
          titleB = '菜单'
        } else if (this.menuType === 3) {
          titleB = '操作'
        } else {
          titleB = '目录'
        }
        return titleF + titleB
      },
      setName() {
        return {
          label: this.radioTypeList[this.menuType - 1],
          placeholder: '请输入' + this.radioTypeList[this.menuType - 1] + '名称'
        }
      },
      setAlias() {
        return {
          label: this.radioTypeList[this.menuType - 1],
          placeholder: '请输入' + this.radioTypeList[this.menuType - 1] + '别名'
        }
      },
      setParentName() {
        return this.menuType < 3 ? '上级目录：' : '上级菜单：'
      }
    },
    methods: {
      init(params) {
        this.dialogVisible = true
        this.dialogType = params.type
        this.menuType = params.menuType
        this.initTree(params.menu)
        if (params.type === 'edit') {
          this.formLoading = true
          const id = params.id
          this.$http.get(this.$http.adornUrl(`/sys/menu/info/${params.id}`)).then(response => {
            const result = response.data
            if (result && result.code === 200) {
              const data = result.data
              this.menuId = data.menuId
              this.dataForm.menuName = data.menuName
              this.dataForm.menuAlias = data.menuAlias
              this.dataForm.pid = data.pid
              this.dataForm.pname = data.pname === null ? '根目录' : data.pname
              this.dataForm.menuType = data.menuType
              this.dataForm.menuOrder = data.menuOrder
              this.dataForm.menuIcon = data.menuIcon
              this.dataForm.menuPath = data.menuPath
              this.dataForm.menuPerm = data.menuPerm
              this.dataForm.menuDesc = data.menuDesc
            } else {
              this.$message({message: result.msg, type: 'error'})
            }
            this.formLoading = false
          }).catch(reason => {
            this.$message({message: reason, type: 'error'})
            this.formLoading = false
          })
        }
      },
      initTree(data) {
        this.treeMenu = [
          {
            id: 0,
            alias: '根目录',
            type: 0,
            children: data
          }
        ]
      },
      formDataSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const data = this.dataForm
            const url = this.dialogType === 'add' ? this.$http.adornUrl('/sys/menu/info') : this.$http.adornUrl(`/sys/menu/info/${this.menuId}`)
            const method =  this.dialogType === 'add' ? 'post' : 'put'
            const tips = this.dialogType === 'add' ? '新增' : '修改'
            this.$http({
              url: url,
              method: method,
              data: this.$http.adornData(data)
            }).then(response => {
              const result = response.data
              if (result && result.code === 200) {
                this.$emit('refreshData')
                this.$message({message: tips + result.msg, type: 'success'})
                this.dialogVisible = false
              }else {
                this.$message({message: tips + result.msg, type: 'error'})
              }
            }).catch(reason => {
              this.$message({message: reason, type: 'error'})
            })
          }
        })
      },
      handlerRadioChange(value) {
        this.menuType = value
        this.dataForm.pid = ''
        this.dataForm.pname = '选择上级资源'
        this.dataForm.menuIcon = ''
        this.dataForm.menuPath = ''
        this.dataForm.menuPerm = ''
      },
      handleTreeCurrentChange(data, node){
        if (this.menuType === 1 && data.type > 1) {
          this.$message({message: '请选择根目录或者目录资源', type: 'info'})
          return
        }
        if (this.menuType === 2 && data.type > 1) {
          this.$message({message: '请选择目录资源', type: 'info'})
          return
        }
        if (this.menuType === 3 && data.type != 2) {
          this.$message({message: '请选择菜单资源', type: 'info'})
          return
        }
        this.dataForm.pid = data.id
        this.dataForm.pname = data.alias
        this.$refs['menuPopover'].doClose()
      },
      closeDialog() {
        this.$refs['dataForm'].resetFields()
        // 以下三个参数由于存在v-if判断为true时不会重置掉，需要再手动重置
        this.dataForm.menuIcon = null
        this.dataForm.menuPerm = null
        this.dataForm.menuPath = null
        this.dataForm.pname = '选择上级资源'
        this.dialogType = ''
        this.menuType = 1
        this.menuId = null;
      }
    }
  }
</script>
<style>
</style>
